<template>
  <a-modal
    title="移动到分组"
    :width="420"
    :visible="visible"
    :confirm-loading="loading"
    :mask-closable="false"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <a-spin :spinning="loading">
      <a-tree
        v-if="groupTreeData.length"
        :selectable="true"
        :block-node="true"
        :tree-data="groupTreeData"
        :auto-expand-parent="true"
        @select="onSelect"
      />
    </a-spin>
  </a-modal>
</template>

<script name="MoveGroup" lang="ts" setup>
import { moveGroup } from "@/api/content/attachFile";

const emit = defineEmits(["submit"]);

const visible = ref(false);
const loading = ref(false);

const selectDataSource = inject<any>("selectDataSource");
const groupTreeData = ref<any>([]);
const fileIds = ref([]);
const selectedKeys = ref([]);

const getList = () => {
  if (groupTreeData.value.length <= 0) {
    const selectItems: any = [
      {
        title: "未分组",
        key: 0,
        value: 0
      }
    ];

    groupTreeData.value =
      selectDataSource != undefined && selectDataSource.value != undefined
        ? selectItems.concat(selectDataSource.value)
        : selectItems;
  }
};

const show = (ids: Array<never>) => {
  visible.value = true;
  fileIds.value = ids;
  getList();
};

const onSelect = (keys: Array<never>) => {
  selectedKeys.value = keys;
};

const handleCancel = () => {
  visible.value = false;
};

const onFormSubmit = () => {
  loading.value = true;

  // 数据提交
  moveGroup({
    groupId: selectedKeys.value[0],
    fileIds: fileIds.value
  })
    .then(() => {
      // 显示成功
      antdMessage.success("操作成功");
      // 关闭对话框
      handleCancel();
      // 通知父端组件提交完成了
      emit("submit");
    })
    .finally(() => {
      loading.value = false;
    });
};

const handleSubmit = () => {
  if (selectedKeys.value.length) {
    onFormSubmit();
  } else {
    handleCancel();
  }
};

defineExpose({ show });
</script>
